package com.neuedu.framework.web.exception;

import com.google.common.base.Throwables;
import com.neuedu.common.constant.HttpStatus;
import com.neuedu.common.core.domain.AjaxResult;
import com.neuedu.common.exception.DemoModeException;
import com.neuedu.common.exception.ServiceException;
import com.neuedu.common.utils.StringUtils;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 全局异常处理器
 *
 * @author neuedu
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());

        return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
    }

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());

        return AjaxResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();

        return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);

        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(UndeclaredThrowableException.class)
    public AjaxResult handleRuntimeException(UndeclaredThrowableException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        Throwable undeclaredThrowable = e.getUndeclaredThrowable();
        String message = undeclaredThrowable.getMessage();
        if (StrUtil.isBlank(message)) {
            message = e.getMessage();
        }

        return AjaxResult.error(message);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);

        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public AjaxResult handleBindException(BindException e) {
        log.error(e.getMessage(), e);
        List<ObjectError> allErrors = e.getAllErrors();
        if (CollectionUtil.isEmpty(allErrors)) {
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.error(allErrors.get(0).getDefaultMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message;
        BindingResult bindingResult = e.getBindingResult();
        FieldError fieldError = bindingResult.getFieldError();
        if (null != fieldError) {
            message = fieldError.getDefaultMessage();
            if (StrUtil.isNotBlank(message)) {
                return AjaxResult.error(message);
            }
        } else {
            List<ObjectError> errors = bindingResult.getAllErrors();
            if (CollectionUtil.isNotEmpty(errors)) {
                message = errors.get(0).getDefaultMessage();
                if (StrUtil.isNotBlank(message)) {
                    return AjaxResult.error(message);
                }
            }
        }

        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(ValidationException.class)
    public AjaxResult handleValidationException(ValidationException e) {
        return processException(e, null);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public AjaxResult handleConstraintViolationException(ConstraintViolationException e) {
        return processException(e, null);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(org.springframework.http.HttpStatus.REQUEST_ENTITY_TOO_LARGE)
    public AjaxResult handleConstraintViolationException(MaxUploadSizeExceededException e) {
        return processException(e, org.springframework.http.HttpStatus.REQUEST_ENTITY_TOO_LARGE.value());
    }

    private AjaxResult processException(RuntimeException e, Integer code) {
        String message = e.getMessage();
        Throwable cause = e.getCause();
        if (null != cause) {
            message = cause.getMessage();
        }
        log.error("Handle exception: {}", Throwables.getStackTraceAsString(e));
        if (null == code) {
            return AjaxResult.error(message);
        } else {
            return AjaxResult.error(code, message);
        }
    }

    /**
     * 演示模式异常
     */
    @ExceptionHandler(DemoModeException.class)
    public AjaxResult handleDemoModeException(DemoModeException e) {
        return AjaxResult.error("演示模式，不允许操作");
    }

}
